var express = require('express');
var router = express.Router();
const userModel = require('../../models/userModel');
const jwt =  require('jsonwebtoken');
//读取配置项
const {secret} = require('../../config/config')


router.post('/login',(req,res)=>{
    //查询数据库
    let {login_name,password} =req.body;
    

    userModel.findOne({user:login_name,password:password})
    .then(data => {
        if(!data){
            return res.json({
                code:"0",
                msg:"账号或密码错误",
                data:null
            })
        }else{
            let token = jwt.sign({
                username:data.user,
                _id:data._id
            },secret,{
                expiresIn:60 * 60 * 24 * 7
            })
            res.json({
                code:"1",
                msg:"登录成功",
                token:token
            })
        }
    })
    .catch(err => {
        res.json({
            code:"0",
            msg:"登录失败,数据库读取失败",
            data:null
        })

    });



  



    
});


module.exports = router;
